package com.tyson.server.config.security;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class JwtTokenUtil {
    private static final String CLAINM_KEY_USERNAME = "sub";
    private static final String CLAINM_KEY_CREATED = "created";

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;


    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAINM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAINM_KEY_CREATED, new Date());
        return this.generateToken(claims);


    }

    public String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(this.generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();

    }

    /**
     * 生成token失效时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }


    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = this.getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            log.error("获取用户名出错啦=》错误信息：", e);

            username = null;
        }
        return username;
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("获取荷载出错啦=》错误信息：", e);
            claims = null;
        }
        return claims;
    }


    /**
     * 验证token是否有效
     *
     * @param token
     * @param userDetails
     * @return ture代表token有效 token还没有过期
     * false代表token无效，token已经过期了
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return String.valueOf(username).equals(userDetails.getUsername()) && !this.isTokenExpired(token);
    }


    /**
     * 验证token是否国企
     *
     * @param token
     * @return true代表token过期啦，已经失效
     * false代表token没有过期，还没有失效
     */
    private boolean isTokenExpired(String token) {
        //获取失效时间
        Date exprieDate = this.getExpireDateFromToken(token);
        //before方法 意思是失效时间在现在时间之前，代表token已失效，返回true
        return exprieDate.before(new Date());
    }


    /**
     * 从token获取失效时间
     *
     * @param token
     * @return
     */
    private Date getExpireDateFromToken(String token) {
        return this.getClaimsFromToken(token).getExpiration();

    }


    /**
     * 判断token是否可以刷新，过期了不能刷新，如果没有过期可以继续刷新
     * @param token
     * @return
     * ture代表未过期，可以刷新
     * false代表已经过期，不能刷新
     */

    public boolean canRefresh(String token){
        return  !isTokenExpired(token);
    }

    /**
     * 刷新token，延长有效期，把token的时间设置为现在
     * @param token
     * @return
     */
    public String refreshToken(String token){
        Claims claims = this.getClaimsFromToken(token);
        claims.put(CLAINM_KEY_CREATED,new Date());
        return this.generateToken(claims);

    }
}